<template>
  <el-scrollbar height="100vh">
    <div class="container">
      <el-affix :offset="1">
        <h1 class="title">旋转地图</h1>
      </el-affix>
      <div id="map" class="map-x" ref="mapBox"></div>
      <el-row class="mb-4" style="margin-top: 20px;">
        <el-button type="success" round @click="rotateLeft()"><el-icon><refresh-right /></el-icon></el-button>
        <el-button type="success" round @click="rotateRight()"><el-icon><refresh-left /></el-icon></el-button>
      </el-row>
      <div class="codestyle"><Code /></div>
      <dl>
        <p>方法：</p>
        <dt>map.getView().getRotation()：获取视图旋转角度</dt>
        <dt>map.getView().setRotation()：设置当前缩放级别</dt>
      </dl>
    </div>
  </el-scrollbar>
</template>
<script>
import Code from './code.vue'
import 'ol/ol.css'
import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ' // 引入XYZ地图格式
import { onMounted, reactive, ref, toRefs } from 'vue-demi'
export default {
  setup () {
    const state = reactive({
      map: null,
      mapBox: ref(null)
    })
    const init = () => {
      state.map = new Map({
        target: state.mapBox,
        layers: [
          new Tile({
            source: new XYZ({
              url: 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'
            })
          })
        ],
        view: new View({
          // 地图视图
          projection: 'EPSG:4326', // 坐标系，有EPSG:4326和EPSG:3857
          center: [116.41400, 39.91500], // 北京坐标
          rotation: 0,
          zoom: 12 // 地图缩放级别（打开页面时默认级别）
        })
      })
    }

    const rotateLeft = () => {
      const currentRotation = state.map.getView().getRotation()
      state.map.getView().setRotation(currentRotation + 1)
    }

    const rotateRight = () => {
      const currentRotation = state.map.getView().getRotation()
      state.map.getView().setRotation(currentRotation - 1)
    }

    onMounted(() => {
      init()
    })
    return {
      ...toRefs(state),
      rotateLeft,
      rotateRight
    }
  },
  components: {
    Code
  }
}
</script>
<style lang="scss" scoped>
@import '../../css/main.scss';
</style>
